<?php

namespace App\Services\Collection;

use App\Exceptions\CollectionException;
use Exception;
use Illuminate\Support\Facades\DB;

class CollectionService extends BaseCollectionService
{
    /**
     * 创建藏品
     *
     * @return void
     * @throws Exception
     */
    public function create(array $params)
    {
        $addData = $this->_handleEditData($params);
        $this->getCollectionModel()->addItem($addData);
    }

    /**
     * 更新藏品
     *
     * @param array $params
     * @return void
     * @throws CollectionException
     * @throws Exception
     */
    public function update(array $params)
    {
        // 查询是否创建过藏品
        $detail = $this->getCollectionModel()->getItemById($params['id']);
        if (empty($detail)) {
            throw new CollectionException('藏品不存在', CollectionException::CODE_1001);
        }

        $updateData = $this->_handleEditData($params);
        $this->getCollectionModel()->updateItemById($params['id'], $updateData);
    }

    /**
     * 删除藏品
     *
     * @return void
     * @throws Exception
     */
    public function delete(array $params)
    {
        // 查询藏品是否存在
        $collection = $this->getCollectionModel()->getItemById($params['id']);
        if (empty($collection)) {
            throw new CollectionException('藏品不存在', CollectionException::CODE_1001);
        }

        // 删除藏品
        DB::transaction(function () use ($params) {
            // 删除藏品
            $this->getCollectionModel()->deleteItemById($params['id']);
            // 删除藏品文件
            $this->getCollectionFilesModel()->deleteItemByCollectionId($params['id']);
        });
    }

    /**
     * 删除藏品
     *
     * @return void
     * @throws Exception
     */
    public function deleteByIds(array $params)
    {
        // 查询藏品是否存在
        $collectionList = $this->getCollectionModel()->getItemsByIds($params['ids']);
        if (empty($collectionList)) {
            throw new CollectionException('藏品不存在', CollectionException::CODE_1001);
        }

        $usedCollectionIds = array_column($collectionList, 'id');

        // 要删除的藏品ids
        $deleteIds = array_intersect($params['ids'], $usedCollectionIds);

        // 批量删除藏品
        DB::transaction(function () use ($deleteIds) {
            // 删除藏品
            $this->getCollectionModel()->deleteItemsByIds($deleteIds);
            // 删除藏品文件
            $this->getCollectionFilesModel()->deleteItemByCollectionIds($deleteIds);
        });
    }

    /**
     * 更新藏品状态
     *
     * @return void
     * @throws Exception
     */
    public function changeStatus(array $params)
    {
        // 查询藏品是否存在
        $collection = $this->getCollectionModel()->getItemById($params['id'], [
            'id', 'status',
        ]);
        if (empty($collection)) {
            throw new CollectionException('藏品不存在', CollectionException::CODE_1001);
        }

        // 查询藏品的文件和封面图是否存在
        $collectionFileList = $this->getCollectionFilesModel()->getListByCollectionId($params['id']);
        if (count($collectionFileList) < 2 && $params['status'] == 1) {
            throw new CollectionException('请先完善藏品文件', CollectionException::CODE_1003);
        }

        // 判断是否需要更新
        if ($collection['status'] == $params['status']) {
            return;
        }
        // 更新藏品状态
        $this->getCollectionModel()->updateItemById($params['id'], [
            'status' => $params['status'],
        ]);
    }

    /**
     * 藏品列表
     *
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function list(array $params): array
    {
        // 获取藏品列表
        $total = $this->getCollectionModel()->total($params);

        $list = $this->getCollectionModel()->list($params, [
            'id', 'title', 'type', 'sub_type as subType', 'status',
        ]);

        return [
            'total'    => $total,
            'list'     => $list,
            'page'     => CURRENT_PAGE,
            'pageSize' => PAGE_SIZE,
        ];
    }

    /**
     * 藏品详情
     *
     * @param array $params
     * @return array
     * @throws CollectionException
     * @throws Exception
     */
    public function detail(array $params): array
    {
        // 查询藏品详情
        $detail = $this->getCollectionModel()->getItemById($params['id'], [
            'id', 'brand_id', 'title', 'type', 'sub_type', 'jump_url', 'jump_type', 'story_content', 'sort',
        ]);
        if (empty($detail)) {
            throw new CollectionException('藏品不存在', CollectionException::CODE_1001);
        }

        return [
            'id'           => $detail['id'],
            'brandId'      => $detail['brand_id'],
            'title'        => $detail['title'],
            'type'         => $detail['type'],
            'subType'      => $detail['sub_type'],
            'jumpUrl'      => $detail['jump_url'],
            'jumpType'     => $detail['jump_type'],
            'storyContent' => $detail['story_content'],
            'sort'         => $detail['sort'],
        ];
    }

    private function _handleEditData($params): array
    {
        return [
            'brand_id'      => $params['brandId'],
            'type'          => $params['type'],
            'sub_type'      => $params['subType'] ?? 0,
            'title'         => $params['title'],
            'jump_url'      => $params['jumpUrl'] ?? '',
            'jump_type'     => $params['jumpType'] ?? 0,
            'story_content' => $params['storyContent'],
            'sort'          => $params['sort'] ?? 0,
        ];
    }
}
